<?php
/**
* This is controller use for public area
* @author: hungnq@younetco.com
* @version: 0.1
*/


class Contest_EntryController extends YouNet_Controller_Action implements Core_Model_IEntryFields{

	/**
	 *
	 * @var Core_Model_Contest
	 */
	private $_contest;
	/**
	 *
	 * @var Core_Model_Entry
	 */
	private $_entry;
	private $_viewState = null;
    private $_pageIds;

    const PARAM_VIEW_STATE = Core_Util::VIEW_STATE_ENTRY;
	public function preDispatch()
	{
		parent::preDispatch();
		$this->_viewState	= time();
		if( $this->getRequest()->getActionName()!='view' )
		{
			$this->view->render('manage/select_fanpages.phtml');
			$this->_preListAction();
			$this->view->use_admin_menu = 1;
		}
	}

	private function _preListAction()
	{
		$idContest		= $this->_getContestId();
		$contestModel	= new Core_Model_DbTable_Contests();

		/* @var $contestRow Core_Model_Contest */
		$contestRow		= $contestModel->findOne($idContest);
        $this->_pageIds = $this->_social->getUserPageIds();
		if(!empty($contestRow->id)
			&& $contestRow->hasAdminPermission($this->_id_user, $this->_pageIds)
		)
		{
			$this->_contest = $contestRow;
		}
		else
		{
			throw new Exception('Bad request',404);
		}
	}

	private function _getContestId()
	{
		$idContest	= $this->_getParam('id_contest', 0);
		$idEntry	= $this->_getParam('id_entry', 0);
		if( $idContest <= 0 && $idEntry <= 0)
		{
			throw new Exception('Bad request',404);
		}
		else if($idEntry >=0)
		{
			$entryModel		= Core_Model_DbTable_Entries::getInstance();
			$entry			= $entryModel->findOne($idEntry);

			if(!empty($entry->id))
			{
				$idContest		= $entry->id_contest;
				$this->_entry	= $entry;
			}
		}
		return $idContest;
	}
	/**
	* This action is the first view when accessing the app
	*/
	public function indexAction()
	{

	}

	public function exportVotersAction()
	{
		require_once("PHPExcel/PHPExcel.php");
        $phpExcel = new PHPExcel();

        $active_sheet = $phpExcel->getActiveSheet();
        $filename       = sprintf('voters-list-report-%d-%s-GMT-0.xls',$this->_entry->id,date('F j, Y, g:i a'));

        $this->_entry->exportVoters($active_sheet,$this->_contest);

        $this->_sendToBrowser($phpExcel, $filename);

//        $this->disableAutoRender();
//
//		$csv_cotent		= $this->_entry->exportVoters();
//		$this->_sendToBrowser($csv_cotent, $filename);
	}

	protected function _sendToBrowser($phpExcel, $filename)
	{
		$phpExcel->setActiveSheetIndex(0);
        //Output the generated excel file so that the user can save or open the file.
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Cache-Control: max-age=0");

        $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
        $objWriter->save("php://output");
        exit;
	}
	public function editAction()
	{
        $backlink = $this->_getBackUrl($this->_contest);
        $currentlink    = $this->view->url();

        $id_entry		=	$this->_getParam('id_entry');
		if(empty($this->_entry->id))
		{
			$entriesTable	=	new Core_Model_DbTable_Entries();
			$this->_entry			=	$entriesTable->findOne($id_entry);
		}

		$candidateInfoTable		= new Core_Model_DbTable_CandidateInfo();
		$candidateInfoRowSet	= $candidateInfoTable->getCandidateInfo($this->_entry->id_user, $this->_entry->id_contest);

		$form = new Tab_Form_Entry(null, $this->_entry->id_contest, Tab_Form_Entry::EDIT);
		$form->getElement('submit')->setLabel($this->translate('LABEL_SAVE'));
		$form->getElement('submit')->setAttrib('class','greenbutton');
        $form->getElement('reset')->setAttrib('class','greenbutton');
        $form->getElement('reset')->setAttrib('onclick',"location.href = \"$currentlink\"");
        $form->getElement('back')->setAttrib('onclick',"location.href = \"$backlink\"");
		$this->view->validate_script = $form->getValidateScript();

		//FIXED: http://jira.younetco.com/browse/FBCONTEST-587
		//$form->setAction($this->view->baseUrl('/contest/entry/edit/id_entry/') . $id_entry);
		$form->setAttrib('class','sm_form standard edit_entry');
		$value = array();

		$contestFieldsTable = new Core_Model_DbTable_EntryFields();
		$contestFields = $contestFieldsTable->getListFieldsBelongToContest($this->_entry->id_contest);
		$field_ids = array();

		/* Get id of first_name, last_name etc fields from candidate info */
		foreach($contestFields as $field)
		{
			$field_ids[$field->type] = $field->id;
		}

		foreach($candidateInfoRowSet as $row)
		{
			$value[$row->id_entry_field] = $row->value;
		}
		if(!empty($field_ids[self::INDEX_DATE_OF_BIRTH]))
		{
			$this->view->index_dob = $field_ids[self::INDEX_DATE_OF_BIRTH];
            if(!empty($value[$field_ids[self::INDEX_DATE_OF_BIRTH]])){
		        $value[$field_ids[self::INDEX_DATE_OF_BIRTH]] =
		            Core_Util::convertDateFormatFromDb2Web($value[$field_ids[self::INDEX_DATE_OF_BIRTH]]);
			}
		}
		$value['title']			= $this->_entry->title;
		$value['description']	= $this->_entry->description;

		$form->populate($value);
		$contestModel	= new Core_Model_DbTable_Contests();
		/* @var $contestRow Core_Model_Contest */
		$contestRow		= $contestModel->findOne($this->_entry->id_contest);

		$this->view->contest =  $contestRow;
		$this->view->entry	 = $this->_entry;
		$this->view->form	 = $form;

		if(isset($_POST['form_submitted']))
		{
			if($form->isValid($_POST))
			{

				$this->_entry->title = $form->getValue('title');
				$this->_entry->description = $form->getValue('description');
				$this->_entry->save();

				//get value such as first name, last name etc.
				$data = $form->getValues();
				$candidate_info = $data['candidate'];

				if(!empty($field_ids[self::INDEX_FIRST_NAME]))
				{
					$format = "%s %s %s";
					$fullname = sprintf(
							$format,
							trim($candidate_info[$field_ids[self::INDEX_FIRST_NAME]]),
							trim($candidate_info[$field_ids[self::INDEX_MIDDLE_NAME]]),
							trim($candidate_info[$field_ids[self::INDEX_LAST_NAME]])
					);
					$candidate_info[$field_ids[self::INDEX_FULL_NAME]] = $fullname;
				}
                if(!empty($field_ids[self::INDEX_DATE_OF_BIRTH]))
                {
                    if(!empty($candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]])){
                        $candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]] =
                            Core_Util::convertDateFormatFromWeb2Db($candidate_info[$field_ids[self::INDEX_DATE_OF_BIRTH]]);
                    }
                }
				$candidateInfoTable->insertFromParams($candidate_info, $this->_entry->id_user);

				$this->view->success_message = $this->translate('MSG_EDIT_SUBMISSION_SUCCESSFUL');
			}
		}
	}

	public function detailAction()
	{
		$id_entry		=	$this->_getParam('id_entry', 0);

		if(!empty($id_entry))
		{
			$entryModel				=	Core_Model_DbTable_Entries::getInstance();
			if(empty($this->_entry->id))
			{
				/* @var $this->_entry Core_Model_Entry */
				$this->_entry					=	$entryModel->findOne($id_entry);
			}

			$contestFieldsModel		=	new Core_Model_DbTable_EntryFields();
			$contestFields			=	$contestFieldsModel->getListFieldsBelongToContest($this->_entry->id_contest);
			$candidateInfo			=	$this->_entry->getCandidateInfo();

			$contestFields = $contestFieldsModel->getListFieldsBelongToContest($this->_entry->id_contest);
			$field_ids = array();

			if(isset($candidateInfo[self::FIELD_FIRST_NAME]))
			{
				unset($candidateInfo[self::FIELD_FULL_NAME]);
			}

			$contestModel	= new Core_Model_DbTable_Contests();
			/* @var $contestRow Core_Model_Contest */
			$contestRow		= $contestModel->findOne($this->_entry->id_contest);

			$this->view->contest		=  $contestRow;
			$this->view->entry			= $this->_entry;
			$this->view->candidateInfo	= $candidateInfo;
			$ref = $this->_getParam('ref', '');
			if (!empty($ref) && $ref == 'email')
				$this->view->back_url       = $this->view->url(array(
					'module'		=> 'contest',
					'controller'	=> 'entry',
					'action'		=> 'list',
					'id_contest'	=> $this->_contest->id
				));
			else
				$this->view->back_url       = $this->_getBackUrl($this->_entry->getContest());

		}
		else
		{
			$this->_forward('list', 'manage');
		}
	}

	public function judgeAction()
	{
		$id_entry	=  $this->_getParam('id_entry');
		if(isset($id_entry))
		{
			$entriesTable		= new Core_Model_DbTable_Entries();
			if(empty($this->_entry->id))
			{
				$this->_entry				= $entriesTable->findOne($id_entry);
			}
			$usersTable			= new Core_Model_DbTable_Users();
			$userRow			= $usersTable->findOne($this->_entry->id_user);

			$form				= new Contest_Form_Judge();
			$values['score1']	= $this->_entry->score1;
			$values['score2']	= $this->_entry->score2;

			$form->populate($values);

			$this->view->form		= $form;
			$this->view->entry		= $this->_entry;
			$this->view->user_link	= $userRow->link;

			if(isset($_POST['form_submitted']))
			{
				if($form->isValid($_POST))
				{
					$this->_entry->score1 = $form->getValue('score1');
					$this->_entry->score2 = $form->getValue('score2');
					$this->_entry->save();
				}
			}
		}
	}

	public function viewAction()
	{
		$id_entry		= $this->_getParam('id_entry');
		$from_page		= $this->_getParam('from_page');
		$id_user_ref	= $this->_getParam('id_user_ref');
		if(isset($id_entry))
		{
			$entriesTable = new Core_Model_DbTable_Entries();
			/* @var $entry Core_Model_Entry */
			$entry = $entriesTable->findOne($id_entry);

			if( !empty($entry) && $entry->isApproved() )
			{
                // Detect requests from another social networks
				if(Core_Util::isSocialNetworksRequest())                
				{
					$this->view->is_facebook	= true;
					$this->view->entry			= $entry;
					$this->view->shareLink       = $this->_social->getShareUrl($entry->getHref() .
					'/from_page/' . $from_page . '/id_user_ref/' . $id_user_ref);
				}
				else
				{
					$params = array('target' => 'detail', 'id_entry' => $id_entry);
					if(!empty($id_user_ref))
					{
						$ns = Zend_Registry::get('session');
						$ns->id_entry = $id_entry;
						$ns->id_user_ref = $id_user_ref;
						$params['id_user_ref'] = $id_user_ref;
					}

					//Disable only increase if:
					//Existing id_user_ref & and correct id_entry
					//Core_Model_DbTable_Entries::getInstance()->increaseShareNumber($id_entry);

					if(!empty($from_page))
					{
						YouNet_Util::parentRedirect(rawurldecode($this->_social->pageUrl($params, trim($from_page))));
					}
					else
					{
						$fanpage = $entry->getFanpage();
						if(count($fanpage->number_of_page) == 1)
						{
							YouNet_Util::parentRedirect($this->_social->pageUrl($params, $fanpage->id_page));
						}
					}
				}
				return;
			}
			if( !empty($from_page) )
			{
                $this->_helper->flashMessenger->addMessage("MGS_ENTRY_CAN_NOT_FOUND");
				$params = array('target' => 'view');
				YouNet_Util::parentRedirect($this->_social->pageUrl($params, $from_page));
				return;
			}
		}
		$this->_social->redirect('/contest/index');
	}

	/**
	 * Cannot getIdPage here
	 * @deprecated
	 * @param type $params
	 * @param type $id_page
	 * @return type
	 */
	private function pageUrl($params, $id_page)
	{
		$app_data = urlencode(json_encode($params));
		return $this->_social->getFanPageUrl($id_page, 'page') . '&app_data=' . $app_data;
	}

	public function listAction()
	{
		$arrSort        = $this->_getParam(PARAM_SORT_DEFAULT,array());
		$page			= $this->_getParam('page',1);
		$idContest		= $this->_contest->id;
		$entryModel		= new Core_Model_DbTable_Entries();
		$arrFilter		= array_merge($arrSort,array(
			Core_Model_IEntry::PARAM_KEYWORD		=> trim($this->_getParam(Core_Model_IEntry::PARAM_KEYWORD,'')),
			Core_Model_IEntry::PARAM_KEYWORD_FILTER => $this->_getParam(Core_Model_IEntry::PARAM_KEYWORD_FILTER),
			Core_Model_IEntry::PARAM_STATUS			=> $this->_getParam(Core_Model_IEntry::PARAM_STATUS),
		));
		$selection		= $entryModel->getSelectionByIdContest($idContest,$arrFilter);
		$paginator      = Zend_Paginator::factory($selection);
		$paginator->setCurrentPageNumber($page);
		$paginator->setItemCountPerPage(LIST_ITEM_ENTRY_PER_PAGE);
        $this->_setViewState($this->_viewState, $idContest);

		$this->view->contest		= $this->_contest;
		$this->view->paginator      = $paginator;
		$this->view->{self::PARAM_VIEW_STATE} = $this->_viewState;
	}

    public function approvelistAction()
    {
        $id_entries = $this->_getParam('id_entries', null);
        if(!empty($id_entries))
        {
            $entriesTable = YouNet_Util::getDbTable("entries");
            $result = $entriesTable->approveListEntries($id_entries, $this->_contest->id);
        }
        $this->_redirectBack($this->_contest);
    }

    public function rejectlistAction()
    {
        $id_entries = $this->_getParam('id_entries', null);
        if(!empty($id_entries))
        {
            $entriesTable = YouNet_Util::getDbTable("entries");
            $result = $entriesTable->rejectListEntries($id_entries, $this->_contest->id);
        }
        $this->_redirectBack($this->_contest);
    }

	public function approveAction()
	{
		$id_entry = $this->_getParam('id_entry', 0);
		if( $id_entry <= 0)
		{
			throw new Exception('Bad request' ,404);
		}
		$this->_changeStatus($id_entry, Core_Model_IEntry::STATUS_APPROVED);
	}
	public function rejectAction()
	{
		$id_entry = $this->_getParam('id_entry', 0);
		if( $id_entry <= 0)
		{
			throw new Exception('Bad request' ,404);
		}
		$this->_changeStatus($id_entry, Core_Model_IEntry::STATUS_REJECT);
	}

	private function _changeStatus($id, $status)
	{
		$entryTable = new Core_Model_DbTable_Entries();

		if(empty($this->_entry->id))
		{
			$entryRow	= $entryTable->findOne($id);
		}
		else
		{
			$entryRow	= $this->_entry;
		}

		/* @var $entryRow Core_Model_Entry */
		if( empty($entryRow->id) )
		{
			throw new Exception('Bad request' ,404);
		}
		$contest = $entryRow->getContest();
		/* @var $contest Core_Model_Contest */
		if( !$contest->hasAdminPermission($this->_id_user, $this->_pageIds) )
		{
			throw new Exception('Access denied',302);
		}
		// Check if contest can submit others entry by a user
		if( $status == Core_Model_IEntry::STATUS_APPROVED )
		{
			if( $contest->hasAdminPermission($entryRow->id_user, $this->_pageIds) || $contest->canApproved($id) )
			{
				$entryRow->status = $status;
				$entryRow->save();
			}
			else
			{
				Core_Util::setLatestMessage(sprintf(YouNet_Util::translate('MSG_CAN_NOT_APPROVED'), '<strong>'.$this->view->escape($entryRow->getCandidateName()).'</strong>' ),'entry_approve');
			}
		}
		else
		{
			$entryRow->status = $status;
			$result = $entryRow->save();
            if( !empty($result) && $status == Core_Model_IEntry::STATUS_DELETE ){
                Core_Model_DbTable_Contests::getInstance()->updateSubmissionInfo($contest->id, array(
                    'submissions' => new Zend_Db_Expr('submissions - 1')
                ));
            }
		}
		//$this->_redirectBack($contest);
         $this->_redirect($this->_getBackUrl($this->_contest),
                            array('prependBase' => false)
                );
	}
	private function _redirectBack($contest)
	{
		$this->disableAutoRender();
		$session		= $this->_getSession();
		$view_state		= 0;
		if( !empty($_COOKIE[self::PARAM_VIEW_STATE . '_' . $contest->id]) )
		{
			$view_state = $_COOKIE[self::PARAM_VIEW_STATE . '_' . $contest->id];
		}
		$arrUrl			= $session->url;
		$url			= '';
		if( $view_state && isset($arrUrl[$view_state]) )
		{
			$url		= $arrUrl[$view_state];
		}
		var_dump($url);
		//Try to avoid loop
		if( !empty($url) && $url != $this->_getCurrentUri() )
		{
			$this->_redirect($url);
		}
		else
		{
			$this->_redirect($this->view->url(array(
				'module'	=> 'contest',
				'controller'=> 'entry',
				'action'	=> 'list',
				'id_contest'=> $contest->id), null, true),array(
					'prependBase' => false
				));
		}
	}

    private function _setViewState($view_state, $id_contest)
    {
        setcookie(self::PARAM_VIEW_STATE . '_' . $id_contest, $view_state, time() + 7200, '/');
    }

    private function _getBackUrl($contest)
	{
		$session		= $this->_getSession();
		$view_state		= 0;

		if( !empty($_COOKIE[self::PARAM_VIEW_STATE . '_' . $contest->id]) )
		{
			$view_state = $_COOKIE[self::PARAM_VIEW_STATE . '_' . $contest->id];
		}
		$arrUrl			= $session->url;

		$url			= '';
		if( $view_state && isset($arrUrl[$view_state]) )
		{
			$url		= $arrUrl[$view_state];
		}
//		//Try to avoid loop
//		if( !empty($url) && $url != $this->_getCurrentUri() )
//		{
//			return $this->_social->url($url);
//		}
//		else
//		{
//			return $this->_social->url('/contest/entry/list/id_contest/'.$contest->id);
//		}
        //Try to avoid loop
		$ref = $this->_getParam('ref' ,'');
		if (!empty($ref) && $ref == 'email')
			return $this->view->baseUrl('/contest/entry/list/id_contest/'.$contest->id);
		if(!empty($url) && $url != $this->_getCurrentUri())
		{
			return $this->view->baseUrl($url);
		}
		else
		{
			return $this->view->baseUrl('/contest/entry/list/id_contest/'.$contest->id);
		}
	}

	public function postDispatch() {
		$url			= $this->_getCurrentUri();
		$session		= $this->_getSession();
		$arrUrl			= $session->url;
		if( empty($arrUrl) || !is_array($arrUrl) )
		{
			$arrUrl = array();
		}

		$arrUrl[$this->_viewState] = $url;
		//Limit 10
        $ind = 0;
		foreach($arrUrl as $key => $value)
		{
			if( count($arrUrl) >= 10 && $ind < count($arrUrl) - 10)
			{
				unset($arrUrl[$key]);
			}
            $ind++;
		}
		$session->url	= $arrUrl;
	}

	private function _getCurrentUri()
	{
		$uri			= $_SERVER['REQUEST_URI'];
		$uri			= substr($uri,strlen($this->view->baseUrl('/')) - 1);
		return $uri;
	}
	/**
	 *
	 * @return \Zend_Session_Namespace
	 */
	private function _getSession()
	{
		$session = Zend_Registry::get('session');
		return $session;
	}
}
